import { useAuthStore } from '~/stores/auth';
import { useLocation, Navigate } from '@remix-run/react';
import { useState, useEffect } from 'react';

export function AuthGuard({ children }: { children: React.ReactNode }) {
  const token = useAuthStore((state) => state.token);
  const location = useLocation();
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    const storedAuth = localStorage.getItem('auth-storage');
    if (storedAuth) {
      const { state } = JSON.parse(storedAuth);
      if (state.token) {
        useAuthStore.setState({ token: state.token, user: state.user });
      }
    }
    setIsClient(true);
  }, []);

  if (!isClient) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="text-gray-600">加载中...</div>
      </div>
    );
  }

  if (!token && !location.pathname.startsWith('/auth/')) {
    return (
      <Navigate
        to="/auth/login"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  return <>{children}</>;
}